﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

// **********************************************************************
// Copyright (C) XM
// Author: 赵思佳
// Date: 2019-01-21
// Desc: 代码逻辑文件
// **********************************************************************
namespace SpaceDFramework
{
    public abstract partial class MonoBehaviourSimplify:MonoBehaviour
    {
        List<MsgRecord> msgRecorder = new List<MsgRecord>();
        public void RegisterMsg(string msgName, Action<string> onMsgReceived) {
            MsgDispacther<string>.Register(msgName, onMsgReceived);
            msgRecorder.Add(MsgRecord.Allocate(msgName,onMsgReceived));
        }
        public void UnRegister(string msgName) {
            var selectRecords = msgRecorder.FindAll(record => record.msgName == msgName);
            selectRecords.ForEach(record =>
            {
                MsgDispacther<string>.UnRegister(record.msgName, record.onMsgReceived);
                msgRecorder.Remove(record);
                record.Recycle();
            });
            selectRecords.Clear();
        }
        public void UnRegister(string msgName,Action<string>onMsgReceiveg)
        {
            var selectRecords = msgRecorder.FindAll(record => record.msgName == msgName && record.onMsgReceived == onMsgReceiveg);
            selectRecords.ForEach(record =>
            {
                MsgDispacther<string>.UnRegister(record.msgName, record.onMsgReceived);
                msgRecorder.Remove(record);
                record.Recycle();
            });
            selectRecords.Clear();
        }
        public abstract void OnBeforeDestory();
        public void OnDestroy()
        {
            OnBeforeDestory();
            foreach (var msgRecord in msgRecorder)
            {
                MsgDispacther<string>.UnRegister(msgRecord.msgName, msgRecord.onMsgReceived);//自动释放事件注册
                msgRecord.Recycle();
            }
            msgRecorder.Clear();
        }
    }
    public class MsgRecord
    {
        public string msgName;
        public Action<string> onMsgReceived;
        static Stack<MsgRecord> mMsgRecordPool = new Stack<MsgRecord>();
        public static MsgRecord Allocate(string msgName, Action<string> onMsgReceived)
        {
            MsgRecord retRecord = mMsgRecordPool.Count > 0 ? mMsgRecordPool.Pop() : new MsgRecord();
            retRecord.msgName = msgName;
            retRecord.onMsgReceived = onMsgReceived;
            return retRecord;
        }
        public void Recycle()
        {
            msgName = null;
            onMsgReceived = null;
            mMsgRecordPool.Push(this);
        }
    }
}
